const fs = require('fs')
const path = require('path')
const query = require('../util/sql')
const officialWebPath = require('../util/uploadPath')
module.exports = async (ctx, next) => {
  const { content, title, type, abstract, author } = ctx.query
  let config = JSON.parse(fs.readFileSync('./config.properties', 'utf-8'))
  let newsId = config.newsId + 1
  let newConfig = JSON.stringify({...config, newsId})
  fs.writeFile('./config.properties', newConfig, err => {
    if (err) throw err
    console.log('文件已保存')
  })
  let main = content.replace(/\"/g, "\'")
  let date = new Date().getTime()
  let data = `{\"main\":\"${main}\",\"date\":\"${date}\",\"title\":\"${title}\",\"type\":\"${type}\",\"author\":\"${author}\",\"abstract\":\"${abstract}\"}`
  newsId = (newsId + '').padStart(5, '0')
  let filename = path.join(officialWebPath, `./dist/json/news/${newsId}.json`)
  fs.writeFile(filename, data)
  console.log('title', title)
  try {
     let sql = `insert into news(date, type, title, abstract, author) values (\"${date}\", ${type}, \"${title}\", \"${abstract}\", \"${author}\")`
     console.log(sql)
     let result = await query(sql)
     ctx.state.data = {message: '录入成功!'}
  } catch(e) {
    console.log(e)
  }
  // let sql = `insert into news(date, type, title, abstract, author) values ("1111111111111", 1, "title", "abstract", "author")`
}